// +----------------------------------------------------------------------
// | CmsWing [ 美业管理系统 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016 psi All rights reserved.
// +----------------------------------------------------------------------
// | Author: huang <2374266244@qq.com>
// +----------------------------------------------------------------------
'use strict';
import Base from './base.js';

export default class extends Base {
	/**
	* index action
	* @return {Promise} []
	*/
	async infolistAction(){
		let poptype = this.get('poptype');
		let keywords = this.get('keywords');
		//根据类型调用相关接口
		if('guest' == poptype){
			this.getguest(keywords);
		}
		let data = {
			"name":12,
			"value":33,
		}
		return this.json(data);	
	}

	async subjectlistAction(){
		let slist = await this.model('or_subject')
					.alias('os')
					.field('os.id,os.name,os.remarks,os.usetime,ot.name as tname')
					.join(think.config('db.prefix')+'or_subjecttype ot on os.t_id=ot.id')
					.where({'os.o_id':this.shop_userinfo.o_id})
					.select();

		let relist = {
			"draw": '',
			"data": slist,
			"breadcrumb":''
		}

		return this.json(relist);
	}

	// 获取店家项目列表
	async getshopsubjectsAction(){
		let slist = await this.model('or_shop_subject')
					.alias('s')
					.field('s.id,s.price,s.subjectid,s.usetime, os.name, os.remarks')
					.join('think_or_subject os on os.id = s.subjectid')
					.where({'s.departmentid':this.shop_userinfo.departmentid})
					.select();
		let relist = {
			"draw": '',
			"data": slist,
			"breadcrumb":''
		}
		return this.json(relist);
	}

	// 获取店家拉取的卡项列表
	async getshopcardsAction(){
		let num = this.post('num');
		let lim = this.post('lim');
		let sea = this.post('sea');

		// 获取新的卡项
		let data = await this.model('or_shop_card')
		.where({shopid: this.shop_userinfo.departmentid, isdisabled: 0, 'name|remarks|price|number':['LIKE','%'+sea+'%']})
		.page(num, lim)
		.countSelect()
		return this.json(data);
	}

	// 获取当前店家的产品列表
	async getshopgoodsAction(){
		let glist = await this.model('or_shop_goods')
					.alias('sg')
					.field('sg.id, sg.price, sg.goodsid, g.name, g.remarks')
					.join('think_or_goods g on g.id = sg.goodsid')
					.where({'sg.departmentid':this.shop_userinfo.departmentid,'sg.isdisable':0})
					.select();
		let relist = {
			"draw": '',
			"data": glist,
			"breadcrumb":''
		}
		return this.json(relist);
	}

	// 获取商品列表
	async getgoodslistAction () {
		let filter = JSON.parse(this.post('filter'))

		let where = {
			'sg.isdisable': filter.isdisabled,
			'sg.shopid': this.shop_userinfo.departmentid
		}

		if (Number(filter.brandid)) where['g.brandid'] = filter.brandid
		if (filter.keywords) where['g.name|g.number'] = ['like', '%' + filter.keywords + '%']

		let list = await this.model('or_shop_goods')
		.alias('sg')
		.field('g.id, sg.price, sg.nums, g.name, g.remarks, g.brandid, g.number')
		.join('think_or_goods g on g.id = sg.goodsid')
		.where(where)
		.page(filter.currentpage, filter.pagesize)
		.countSelect();

		return this.json(list)
	}

	// 获取品牌列表接口
	async getbrandlistAction () {
		/*let did = await this.model('or_department').where({id: this.shop_userinfo.departmentid}).getField('pid', true)
		let list = await this.model('or_brand').where({isdisabled: 0, departmentid: did}).select()*/
		let shopid = this.shop_userinfo.departmentid;
		let data = await this.model('or_shop_goods')
				.alias('sg')
				.field('b.*')
				.join('`think_or_goods` g on g.id=sg.goodsid')
				.join('`think_or_brand` b on b.id=g.brandid')
				.where({'sg.shopid': shopid}) 
				.select();
 
		let list = [];
		let idlen = [];
		data.forEach((res)=>{
			if(idlen.indexOf(res.id) === -1){
				idlen.push(res.id) 
				list.push(res)
			}
		}) 
		return this.json(list)
	}

	// 获取当前店家产品和项目列表
	async getpinxiangAction(){
		let shopid = this.shop_userinfo.departmentid;

		let products = await this.model().query('select sg.*,g.name,g.remarks,g.brandid,g.categoryid,"false" as isuse from `think_or_shop_goods` sg left join `think_or_goods` g on g.id=sg.goodsid where sg.shopid='+shopid+' and sg.isdisable=0');

		let projects = await this.model().query('select ss.*,s.name,s.remarks,s.brandid,s.categoryid,"false" as isuse from `think_or_shop_subject` ss left join `think_or_subject` s on s.id=ss.subjectid where ss.shopid='+shopid+' and ss.isdisable=0');

		let data = {
			goods : products,
			subjs : projects
		}
		return this.json(data);
	}

	// 获取客户列表api
	async getguestlistAction () {
		let filter = this.post();
		let where = {
			'g.isdisable': 0,
			'g.name|g.username|g.vipcard': ['like', '%' + filter.search + '%'],
			'g.departmentid': this.shop_userinfo.departmentid,
			'g.initial_info': 1
		}
		let data = await this.model('or_guest')
				.alias('g')
				.field('g.*, v.vipname, v.goodsdiscount, v.subjectdiscount')
				.join('left join `think_or_guest_vipgrade` v on g.level = v.id')
				.where(where)
				.page(filter.currentpage, filter.pagesize)
				.order('g.id DESC')
				.countSelect();
		return this.json(data)
	}

	// 获取跨店客户信息
	async getDepartmentGuestListAction () {
		let filter = this.get();
		let departmentid = await this.model('or_department').where({id: this.shop_userinfo.departmentid}).getField('pid', true)
		let shopList = await this.model('or_department').where({pid: departmentid, floor: 1, isdisable: 0}).getField('id')
		let where = {
			'g.isdisable': 0,
			'g.name|g.username|g.vipcard': ['like', '%' + filter.search + '%'],
			'g.departmentid': ['IN', shopList],
			'g.initial_info': 1
		}
		let data = await this.model('or_guest')
				.alias('g')
				.field('g.*, d.name as shopname, v.vipname, v.goodsdiscount, v.subjectdiscount')
				.join('left join `think_or_guest_vipgrade` v on g.level = v.id')
				.join('left join `think_or_department` d on g.departmentid = d.id')
				.where(where)
				.page(filter.currentpage, filter.pagesize)
				.order('g.id DESC')
				.countSelect();
		return this.json(data)
	}

	//获取项目分类列表
	async getsubjectcategorylistAction () {
		/*let did = await this.model('or_department').where({id: this.shop_userinfo.departmentid}).getField('pid', true)
		let list = await this.model('or_subjectcategory').where({departmentid: did, isdisable: 0}).select()*/
		let shopid = this.shop_userinfo.departmentid;
		let data = await this.model('or_shop_subject')
				.alias('s')
				.field('sc.*')
				.join('`think_or_subject` ss on ss.id = s.subjectid') 
				.join('think_or_subjectcategory sc on sc.id=ss.categoryid')
				.where({shopid:shopid}) 
				.select()
		let list = [];
		let idlen = [];
		data.forEach((res)=>{
			if(idlen.indexOf(res.id) === -1){
				idlen.push(res.id) 
				list.push(res)
			}
		}) 
		return this.json(list)
	}

	// 获取店家项目列表
	async getsubjectlistAction () {
		let page = this.post();
		let pages = page.pages;
		let limits = page.limits;
		let search = page.search;
		let cid = page.cid;
		let shopid = this.shop_userinfo.departmentid;

		let where = {
			's.isdisable': 0,
			's.shopid': shopid,
		}

		if (search != '') where['o.name|o.number'] = ['like', '%' + search + '%'];
		if (cid*1 != 0) where['o.categoryid'] = cid;

		let list = await this.model('or_shop_subject')
				.alias('s')
				.field('o.id, s.price, s.usetime, o.name, o.remarks, o.brandid, o.number')
				.join('`think_or_subject` o on s.subjectid = o.id')
				.where(where)
				.page(pages, limits)
				.countSelect();

		return this.json(list)
	}

	// 获取客户的卡列表
	async getguestcardlistAction () {
		let id = this.get('guestid') 
		let shopid = this.shop_userinfo.departmentid; 
		let list = await this.model('or_shop_card').where({shopid:shopid}).select()
		return this.json(list)
	}

	// 获取客户的卡项列表
	async getguestcardsubjectlistAction () {
		let filter = JSON.parse(this.post('filter'))
		let nowtime = Math.round(Date.parse(new Date())/1000) // 当前时间
		// 先按照次数和剩余天数判断是否到期
		let where = 'gs.guestid = ' + filter.guestid
		where += ' and gs.isdisabled = 0'
		// 期卡到期时间 nowtime > addtime+validity*86400 and cardtypeid = 1 次卡到期：nownum > 0 and cardtypeid = 2
		where += ' and ((' + nowtime + ' < gs.endtime and gs.cardtype = 1) or (gs.nownum > 0 and gs.cardtype = 2))'
		if (filter.keywords) where += ' and (s.name like "%' + filter.keywords + '%" or s.number like "%' + filter.keywords + '%")'
		if (filter.cardid && filter.cardid != 0) where += ' and gs.cardid = ' + filter.cardid

		// 重新获取数据
		let subjectlist = await this.model('or_shop_guestcardsubject')
		.alias('gs')
		.field('gs.*, s.name, s.brandid, c.name as cardname, cs.xhprice')
		.join('left join `think_or_subject` s on gs.subjectid = s.id')
		.join('left join `think_or_shop_card` c on gs.cardid = c. id')
		.join('left join `think_or_shop_cardsubject` cs on gs.cardid = cs.cardid and gs.subjectid = cs.subjectid')
		.where(where)
		.page(filter.currentpage, filter.pagesize)
		.countSelect()

		return this.json(subjectlist)
	}
	// 获取客户暂存商品
	async getgueststoreAction () {
		let filter = JSON.parse(this.post('filter'))
		let where = {
			'tr.guestid': filter.guestid,
			'tr.nownum': ['>', 0],
			'tr.isdisabled': 0
		}
		if (filter.keywords) where['g.name|g.number'] = ['like', '%' + filter.keywords + '%']
		// 获取客户暂存的项目和产品
		let list = await this.model('or_shop_guest_temp_reserve')
		.alias('tr')
		.field('tr.*, g.name')
		.join('left join `think_or_goods` g on tr.goodsid = g.id')
		.where(where)
		.page(filter.currentpage, filter.pagesize)
		.countSelect();
		

		return this.json(list)
	}

	// 获取收款账户
	async getaccountlistAction () {
		let filter = JSON.parse(this.post('filter'))
		let where = {
			departmentid: this.shop_userinfo.departmentid,
			isdisable: 0
		}
		if (filter.keywords) where['name|number'] = ['like', '%' + filter.keywords + '%']

		let list = await this.model('or_shop_account').where(where).page(filter.currentpage, filter.pagesize).select()
		let count = await this.model('or_shop_account').where(where).count()
		let data = {
			list: list,
			count: count
		}
		return this.json(data)
	}

	// 获取分店的员工列表
	async getappuserAction () {
		let filter = JSON.parse(this.post('filter'));
		let guestid = this.post('gid');
		let allot = [];
		let shopid = this.shop_userinfo.departmentid;
		if (guestid) {
			allot = await this.model('or_allotuser')
							.alias('a')
							.join('`think_or_app_user` u on u.id=a.uid')
							.where({'a.gid': guestid})
							.getField('a.uid');
		}
		let where = {
			'u.shopid': shopid,
			'u.isdisable': 0,
			'u.isdelete': 0
		}
		if (filter.keywords) where['u.name|u.worknum'] = ['like', '%' + filter.keywords + '%']
		if (filter.ismanage) where['u.ismanage'] = filter.ismanage

		let list = await this.model('or_app_user')
							.alias('u')
							.field('if(p.name!="",p.name,"暂无") as zcname, u.*')
							.join('`think_or_position` p on p.id=u.zhichengid')
							.where(where)
							.page(filter.currentpage, filter.pagesize)
							.select()
		let count = await this.model('or_app_user').alias('u').where(where).count()
		let data = {
			aid: allot,
			list: list,
			count: count
		}
		return this.json(data)
	}

	// 获取有卡的客户列表
	async getcardguestsAction(){
		let page = JSON.parse(this.post('page'));
		let pages = page.pages;
		let limits = page.limits;
		let search = page.search;
		let shopid = this.shop_userinfo.departmentid;

		let list = await this.model('or_guest')
					.alias('g')
					.field('g.*')
					.join('think_or_shop_guestcard gc on gc.guestid = g.id')
					.where({'gc.departmentid': shopid,'g.name|g.phone|g.vipcard':['like','%'+search+'%'],'g.isdisable':0,'gc.status':1,'g.initial_info':1})
					.page(pages, limits)
					.order('g.id DESC')
					.group('g.id')
					.select();
		let data = {
			list : list,
			count : list.length
		}
		return this.json(data);
	}

	// 获取卡的项目
	async getcardsubjectlistAction () {
		let id = this.post('id')
	}

	async categorylistAction(){
		let departmentid = await this.model('or_department').where({id: this.shop_userinfo.departmentid}).getField('pid', true)
		let plist = await this.model().query('SELECT * FROM think_or_subjectcategory WHERE departmentid='+departmentid+' AND pid=0');
		let clist = await this.model().query('SELECT * FROM think_or_subjectcategory WHERE departmentid='+departmentid+' AND pid!=0');
		let data = {
			p: plist,
			c: clist
		}
		return this.json(data);
	}
}